<template>
  <div class="data-manage">
    <!-- 搜索条件和新增按钮面板 -->
    <div class="topSearch">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item class="s1" label="名称">
          <el-input v-model="queryParams.filter.monitorPointName" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item class="s2" label="安装时间">
          <el-date-picker v-model="queryRangeDate" type="daterange" range-separator="-" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item class="s1" label="安装地址">
          <el-input v-model="queryParams.filter.address" placeholder="安装地址"></el-input>
        </el-form-item>
        <el-form-item class="s1" label="运行状态">
          <el-input v-model="queryParams.filter.status" placeholder="运行状态"></el-input>
        </el-form-item>


        <el-button class="sysButton" type="primary" @click="onQuery">查询</el-button>
        <el-button class="sysButton" type="primary" @click="resetQueryparm">重置条件</el-button>
        <el-button class="sysButton" type="primary" @click="openMonitorDialog">新增巢箱</el-button>
        <el-button class="sysButton" type="primary" @click="openUnitDialog">安装单位管理</el-button>
        <!-- <el-button class="sysButton" type="primary" @click="test">测试</el-button> -->
      </el-form>
    </div>
    <!-- 巢箱数据列表 -->
    <div class="tab">
      <el-table ref="multipleTable" stripe :data="tableData" tooltip-effect="dark" style="width: 100%; height: 95%;"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="序号" type="index">
          <!-- <template slot-scope="scope">{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column prop="monitorPointName" label="名称">
        </el-table-column>
       
        <el-table-column prop="serialNo" label="序列号">
        </el-table-column>
        <el-table-column prop="address" label="安装地址">
        </el-table-column>
        <el-table-column prop="installDate" label="安装时间">
        </el-table-column>
        <el-table-column prop="status" label="运行状态">
        </el-table-column>
         <el-table-column prop="temperature" label="温度">
        </el-table-column>
        <el-table-column prop="humidness" label="湿度">
        </el-table-column>
        <el-table-column prop="batteryPercentage" label="电量">
        </el-table-column>
        <el-table-column prop="activeTime" label="活跃时间">
        </el-table-column>
        <el-table-column prop="imageUrl" label="图像">
          <template slot-scope="scope">
            <div><img style="width: 80px; height: 80px;" :src="`${$imageServer}${scope.row.imageUrl}`" alt=""></div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="维护账户">
        </el-table-column>
        <el-table-column prop="set" label="操作">
          <template slot-scope="scope">
            <i style="cursor: pointer;" @click="openEditMonitorDialog(scope.row)" class="el-icon-edit"></i>
            <i style="cursor: pointer; margin-left: 10px;" @click="deleteMonitorPoint(scope.row)"
              class="el-icon-delete"></i>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :total="pageParams.total" :currentPage="pageParams.currentPage"
        :pageSize="pageParams.pageSize" @handleCurrentChange="handleCurrentChange"></Pagination>
    </div>
    <!-- 巢箱信息面板 -->
    <el-dialog :title=dialogName :visible.sync="monitorPointDialogVisible" top="10vh" width="30%">

      <el-form label-position="right" label-width="80px" :model="MonitorPointForm">
        
        <el-form-item label="名称">
          <el-input clearable style="width: 300px;" v-model="MonitorPointForm.monitorPointName"></el-input>
        </el-form-item>
        <el-form-item label="序列号">
          <el-input clearable style="width: 300px;" v-model="MonitorPointForm.SerialNo"></el-input>
        </el-form-item>
        <el-form-item label="安装地址">
          <el-input clearable style="width: 300px;" v-model="MonitorPointForm.address"></el-input>
        </el-form-item>
        <el-form-item label="安装单位">
          <el-select v-model="MonitorPointForm.unitId" placeholder="请选择">
            <el-option v-for="item in unitNames" :key="item.key" :label="item.label" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装时间">
          <el-date-picker v-model="MonitorPointForm.installDate" type="date" placeholder="选择安装时间"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="经度">
          <el-input clearable type="number" @input="checkNum('lon')" style="width: 2.2rem;"
            v-model="MonitorPointForm.lon"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input clearable type="number" @input="checkNum('lat')" style="width: 2.2rem;"
            v-model="MonitorPointForm.lat"></el-input>
        </el-form-item>
        <el-form-item label="海拔">
          <el-input clearable type="number" @input="checkNum('alt')" style="width: 2.2rem;"
            v-model="MonitorPointForm.alt"></el-input>
        </el-form-item>
        <el-form-item label="鸟巢朝向">
          <el-select v-model="MonitorPointForm.direction" placeholder="请选择">
            <el-option v-for="item in optionsDirection" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图像">

          <el-upload class="avatar-uploader" action="blank" :show-file-list="false" accept=".jpg, .png"
            :before-upload="beforeAvatarUpload">

            <img v-if="MonitorPointForm.imageUrl" :src="MonitorPointForm.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>

          </el-upload>
          <el-tag>只能上传jpg/png文件，且不超过1mb</el-tag>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <!-- <el-button class="sysButton" @click="handleCancel">取 消</el-button> -->
        <el-button class="sysButton" style="background: bule;" type="primary" @click="addMonitoringPoint">确定</el-button>
      </span>
    </el-dialog>

    <!-- 安装单位面板 -->
    <el-dialog title="安装单位管理" :visible.sync="unitDialogVisible" top="10vh" width="500px">

      <el-form label-position="right" label-width="80px" :model="MonitorPointForm" style="display: flex; " inline>
        <el-form-item label="安装单位">
          <el-input v-model="addUnitParams.unitName" clearable style="width: 250px;"></el-input>
        </el-form-item>
        <el-button class="sysButton" type="primary" @click="addUnit">保存</el-button>
      </el-form>

      <el-table :data="unitNames" style="width: 100%">
        <el-table-column label="序号" type="index">
        </el-table-column>
        <el-table-column prop="label" label="单位名称">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteUnit(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../../components/commons/Pagination.vue";
import { CreateMonitoringPoint } from '../../../api/index';
import { GetMonitoringPointPage } from '../../../api/index';
import { getUnitsName } from '../../../api/index';
import { AddUnit } from '../../../api/index';
import { DeleteUnit } from '../../../api/index';
import { DeleteMonitorPoint } from '../../../api/index';

export default {
  name: 'DataManage',
  components: {
    Pagination,
  },
  data() {
    return {

      addUnitParams: {
        unitName: ""
      },
      unitNames: [
        // {
        //   "umID": "7257667675865432064",
        //   "unitName": "武汉江夏客厅",
        //   "monitoringPoints": []
        // }
      ],
      dialogName: '新增巢箱',
      queryRangeDate: [],
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      //分页参数和查询条件
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        filter: {
          monitorPointName: '',
          address: '',
          startTime: '',
          endTime: '',
          // status:0
        }
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      //安装单位
      optionsInstallUnit: [],
      //鸟巢朝向枚举
      optionsDirection: [{
        value: 0,
        label: '未知方向'
      }, {
        value: 1,
        label: '东'
      }, {
        value: 2,
        label: '南'
      }, {
        value: 3,
        label: '西'
      }, {
        value: 4,
        label: '北'
      }, {
        value: 5,
        label: '东北'
      }, {
        value: 6,
        label: '东南'
      }, {
        value: 7,
        label: '西北'
      }, {
        value: 8,
        label: '西南'
      }
      ],
      //巢箱列表
      tableData: [
      ],
      //表单窗体开关
      monitorPointDialogVisible: false,
      //安装单位窗体开关
      unitDialogVisible: false,
      //表单信息
      MonitorPointForm: {
        SerialNo: '',
        monitorPointName: '',
        address: '',
        lon: 0,
        lat: 0,
        alt: 0,
        direction: 0,
        installDate: new Date(),
        imageUrl: "",
        file: null,
      }
    };
  },
  methods: {
    test() {
  
      this.pageParams.currentPage = 2;

    },
    resetQueryparm() {
      this.pageParams.currentPage = 1;
      this.queryRangeDate = [];
      this.queryParams.currentPage = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.filter.monitorPointName = '';
      this.queryParams.filter.address = '';
      this.queryParams.filter.startTime = '';
      this.queryParams.filter.endTime = '';
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    //限制经纬度输入
    checkNum(inputName) {
      var value = this.MonitorPointForm[inputName];
      if (!value) {
        this.MonitorPointForm[inputName] = 0
      }
    },
    //检查表单内容
    checkFormState() {
      if (!this.MonitorPointForm.monitorPointName) {
        this.$message.error('巢箱名称不允许为空!');
        return false;
      }
      return true
    },
    beforeAvatarUpload(file) {
      if (file.size > 1024 * 1024 * 1) {
        this.$message.error('选择的图片文件超过1mb!');
        return
      };
      this.MonitorPointForm.imageUrl = URL.createObjectURL(file);
      this.MonitorPointForm.file = file;
    },
    openUnitDialog() {
      this.unitDialogVisible = true;

      getUnitsName().then(res => {
        if (res.data.data.length > 0) {
          this.unitNames = [];
          res.data.data.forEach(unit => {
            const newItem = {
              label: unit.unitName,
              key: unit.umID
            };
            //显示所有单位名称
            this.unitNames.push(newItem);
          })
        }
      }
      ).catch(error => {
        console.error("An error occurred:", error);
      })

    },
    openMonitorDialog() {
      getUnitsName().then(res => {
        if (res.data.data.length > 0) {
          this.unitNames = [];
          res.data.data.forEach(unit => {
            const newItem = {
              label: unit.unitName,
              key: unit.umID
            };
            //显示所有单位名称
            this.unitNames.push(newItem);
          })
        }
      }
      ).catch(error => {
        console.error("An error occurred:", error);
      })
      this.dialogName = '新增巢箱'
      //初始化表单
      this.MonitorPointForm.SerialNo = '',
      this.MonitorPointForm.monitorPointName = '',
        this.MonitorPointForm.address = '',
        this.MonitorPointForm.lon = 0,
        this.MonitorPointForm.lat = 0,
        this.MonitorPointForm.alt = 0,
        this.MonitorPointForm.direction = 0,
        this.MonitorPointForm.installDate = new Date(),
        this.MonitorPointForm.imageUrl = "",
        this.MonitorPointForm.file = null,
        this.monitorPointDialogVisible = true;
    },
    onQuery() {
      //debugger
      this.pageParams.currentPage = 1;
      this.queryParams.currentPage = 1;
      if (this.queryRangeDate.length == 2) {
        this.queryParams.filter.startTime = this.formatDate(new Date(this.queryRangeDate[0]));
        this.queryParams.filter.endTime = this.formatDate(new Date(this.queryRangeDate[1]));
      }
      this.excuteQuery();
    },
    handleCurrentChange(val) {
      this.pageParams.currentPage = val; 
      this.queryParams.currentPage = val;
      //查询巢箱信息
      this.excuteQuery();

    },
    handleSelectionChange(a, b) {

    },
    openEditMonitorDialog(row) {
      //修改DIALOG名称为编辑巢箱
      this.dialogName = '编辑巢箱'
      //复制选择对象到面板绑定对象MonitorPointForm
      Object.assign(this.MonitorPointForm, row);
      //修改数据中的图像地址，因为之前使用 全局变量图片服务器地址 在前端模版上绑定的
      this.MonitorPointForm.imageUrl = this.$imageServer + this.MonitorPointForm.imageUrl;
      this.dialogVisible = true;

    },
    deleteMonitorPoint(row) {
      //debugger
      this.$confirm('此操作将删除该巢箱数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let deleteMonitorPointParam = { id: row.umID };
        DeleteMonitorPoint(deleteMonitorPointParam).then(res => {
          // debugger
          if (res.status != 200) {
            this.$message.error(res.data.msg);
          }

          this.onQuery();//删除后重新查询数据

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        ).catch(error => {
          console.error("An error occurred:", error);
        })
      })
    },
    //添加单位
    addUnit() {
      if (this.addUnitParams.unitName.trim() == "") {
        return
      }
      AddUnit(this.addUnitParams).then(res => {
        this.$message({
          message: '添加单位成功！',
          type: 'success'
        });
        getUnitsName().then(res => {
          if (res.data.data.length > 0) {
            this.unitNames = [];
            res.data.data.forEach(unit => {
              const newItem = {
                label: unit.unitName,
                key: unit.umID
              };
              //显示所有单位名称
              this.unitNames.push(newItem);
            })
          }
        }
        ).catch(error => {
          console.error("An error occurred:", error);
        })

      }
      ).catch(error => {
        this.$message.error('添加单位失败！');
        console.error("An error occurred:", error);
      })

    },
    //添加巢箱
    addMonitoringPoint() {
      //debugger
      var isValid = this.checkFormState();
      if (!isValid) {
        return
      }
      // const postData = {
      //   monitorPointName: "7777",
      //   address: "The Address of the Monitoring Point123",
      //   lon: 123.456, // 经度  
      //   lat: 78.901, // 纬度  
      //   alt: 23.45,  // 海拔（可选）  
      //   direction: 0, // 方向（可选）  
      //   projectId: "Your Project ID",
      //   file: this.imageFile
      // };
      const formData = new FormData();
      // for (const key in this.MonitorPointForm) {
      //   if (this.MonitorPointForm.hasOwnProperty(key)) {
      //     formData.append(key, this.MonitorPointForm[key]);
      //   }
      // }
      formData.append("monitorPointName", this.MonitorPointForm.monitorPointName);
      formData.append("address", this.MonitorPointForm.address);
      formData.append("lon", this.MonitorPointForm.lon);
      formData.append("lat", this.MonitorPointForm.lat);
      formData.append("alt", this.MonitorPointForm.alt);
      formData.append("direction", this.MonitorPointForm.direction);
      formData.append("file", this.MonitorPointForm.file);
      formData.append("installDate", this.formatDate(this.MonitorPointForm.installDate));


      CreateMonitoringPoint(formData).then(res => {
        console.log(res)
        //debugger
        if (res.data.msg != '') {
          this.$message.error(res.data.msg);
        }
        else {
          this.$message.success('添加巢箱数据成功');
        }
      }
      ).catch(error => {
        console.error("An error occurred:", error);
      })

    },
    handleCancel() {
      this.dialogVisible = false;
    },
    excuteQuery() {
      GetMonitoringPointPage(this.queryParams).then(res => {
        if (res.status != 200) {
          this.$message.error(res.data.msg);
        }
        this.tableData = res.data.data;
        this.tableData.forEach(item => {
          item.installDate = this.formatDate(new Date(item.installDate));

        });
        this.pageParams.total = res.data.total;
      }
      ).catch(error => {
        console.error("An error occurred:", error);
      })
    },

    deleteUnit(row) {
      this.$confirm('此操作将删除该单位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let deleteUnitParam = { id: row.key };
        DeleteUnit(deleteUnitParam).then(res => {
          //debugger
          if (res.status != 200) {
            this.$message.error(res.data.msg);
          }
          getUnitsName().then(res => {
            if (res.data.data.length > 0) {
              this.unitNames = [];
              res.data.data.forEach(unit => {
                const newItem = {
                  label: unit.unitName,
                  key: unit.umID
                };
                //显示所有单位名称
                this.unitNames.push(newItem);
              })
            }
          }
          ).catch(error => {
            console.error("An error occurred:", error);
          })

        }
        ).catch(error => {
          console.error("An error occurred:", error);
        })

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });


    }

  },
  mounted() {
    //查询所有巢箱信息
    this.excuteQuery();

  }
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
  border: 1px dashed #080808;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 2.2rem;
  height: 1.8rem;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 42px;
  width: 2.2rem;
  height: 1.8rem;
  line-height: 1.8rem;
  text-align: center;
}

.avatar {
  width: 2.2rem;
  height: 1.8rem;
  display: block;
}

.topSearch {
  margin-bottom: 20px;
  height: 76px;
  background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
  display: flex;
  align-items: center;
  padding: 0 25px;


}

.sysButton {
  width: 98px;
  height: 32px;
  background: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid;
  border-image: linear-gradient(216deg, rgba(178, 255, 181, 0) 16%, rgba(178, 255, 181, 0.27) 78%) 1;
}

.tab {
  height: calc(100vh - 240px);
  padding: 20px;
  background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
}

::v-deep {
  .el-dialog {
    // background: #fff;
    background: rgba(33, 124, 147, 0.7);

    .el-dialog__header {
      border-bottom: 1px solid white;
    }

    .el-dialog__title {
      color: #fff
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: #fff
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;

      .el-button {
        color: #fff;
      }
    }

    .el-form-item__label {
      color: #fff;
    }
  }

  .topSearch {
    .el-form {
      display: flex;
      width: 100%;
      justify-content: space-between;

      .el-form-item {
        margin-bottom: 0;
      }

      .el-form-item__label {
        color: #fff;
        margin-right: 10px;
      }
    }
  }

  .s1 {
    .el-input__inner {
      width: 246px;
      height: 32px;
      background: rgba(18, 28, 38, 0.1);
      border: none;
      color: #fff;
    }
  }

  .s2 {
    .el-input__inner {
      height: 40px;
      background: rgba(18, 28, 38, 0.1);
      color: #fff;
      border: none;
    }

    .el-range-separator {
      color: #fff;
    }

    .el-range-input {
      background: none;
    }
  }


  .el-table {
    overflow-y: auto;
    background: transparent;
    border: none;
  }

  .el-table::before {
    height: 0;
  }

  .el-table__header-wrapper tr {
    height: 40px;
    background: linear-gradient(90deg, rgba(115, 255, 247, 0.208) 0%, rgba(115, 255, 247, 0.16) 100%) !important;

    .el-checkbox__inner {
      background: transparent;
      border: 1px solid rgba(115, 255, 247, 0.5);
    }
  }

  .el-table .el-table__cell {
    background: none !important;
    height: 40px;
    color: #fff;
    font-weight: normal;
    border: none !important;
    text-align: center;
  }

  .el-table__body {
    .el-table__row {
      height: 100px;
      background: transparent;
      color: #fff;

      .el-checkbox__inner {
        background: transparent;
        border: 1px solid rgba(115, 255, 247, 0.5);
      }
    }

    .el-table__row--striped {
      background: linear-gradient(90deg, rgba(115, 255, 247, 0.078) 0%, rgba(115, 255, 247, 0.06) 100%);

    }
  }
}
</style>
